<template>
  <div class="app-container search-list" ref="container">
    <el-card class="box-card site" shadow="false">
      <div slot="header" class="clearfix">
        <router-link :to="{name: 'reviews-list'}">
          <el-button plain icon="el-icon-back" size="small" :round="true">
            返回
          </el-button>
        </router-link>

        <div class="oct-container__data">
          <div class="oct-container__data_inner oct-container__data_inner-flex">
            <div style="display: flex; align-items: center;">
              <a :style="{background: `url(${spuInfo.image}) center center / cover no-repeat rgb(238, 238, 238)`} "
                style="display: inline-block;width: 116px; height: 116px; cursor: auto; margin-right: 19px;"></a>
            </div>
            <div class="info">
              <h2 class="header two_line_text_truncate">{{spuInfo.name}}</h2>
              <div class="stars">
                <el-rate v-model="spuInfo.star"
                         :colors="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                         disabled
                         show-score
                         text-color="rgb(244, 90, 25)"
                         score-template="{value}"
                ></el-rate>
                <div style="color: rgb(244, 90, 25); display: flex; align-items: center;"></div>
              </div>
              <div class="footer">
                <span class="item">已发布评论:&nbsp;<span class="text-truncate num">{{spuInfo.published}}</span></span>
                <span class="item">未发布评论:&nbsp;<span class="text-truncate num">{{spuInfo.unPublished}}</span></span>
              </div>
            </div>
            <div class="grade">
              <div class="row">
                <el-rate :value="5"
                         :colors="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                         disabled
                         text-color="rgb(244, 90, 25)"></el-rate>
                <el-progress class="progress" :show-text="false" :percentage="spuInfo.fiveStarPercent"  :stroke-width="12"
                             :color="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                             stroke-linecap="butt"></el-progress>
                <span>{{spuInfo.fiveStarNumber}}</span>

              </div>
              <div class="row">
                <el-rate :value="4"
                         :colors="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                         disabled
                         text-color="rgb(244, 90, 25)"></el-rate>
                <el-progress class="progress" :show-text="false" :percentage="spuInfo.fourStarPercent" :stroke-width="12"
                             :color="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                             stroke-linecap="butt"></el-progress>
                <span>{{spuInfo.fourStarNumber}}</span>

              </div>
              <div class="row">
                <el-rate :value="3"
                         :colors="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                         disabled
                         text-color="rgb(244, 90, 25)"></el-rate>
                <el-progress class="progress" :show-text="false" :percentage="spuInfo.threeStarPercent" :stroke-width="12"
                             :color="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                             stroke-linecap="butt"></el-progress>
                <span>{{spuInfo.threeStarNumber}}</span>

              </div>
              <div class="row">
                <el-rate :value="2"
                         :colors="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                         disabled
                         text-color="rgb(244, 90, 25)"></el-rate>
                <el-progress class="progress" :show-text="false" :percentage="spuInfo.twoStarPercent" :stroke-width="12"
                             :color="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                             stroke-linecap="butt"></el-progress>
                <span>{{spuInfo.twoStarNumber}}</span>
              </div>
              <div class="row">
                <el-rate :value="1"
                         :colors="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                         disabled
                         text-color="rgb(244, 90, 25)"></el-rate>
                <el-progress class="progress" :show-text="false" :percentage="spuInfo.oneStarPercent" :stroke-width="12"
                             :color="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                             stroke-linecap="butt"></el-progress>
                <span>{{spuInfo.oneStarNumber}}</span>
              </div>
            </div>
          </div>
        </div>

        <table-pagination
            size="small"
            ref="el-search-table"
            :fetch="getData"
            type="remote"
            :autoHeight="true"
            :page-sizes="[20, 50, 100]"
            :columns="columns"
            :form-options="formOptions"
            list-field="records"
            total-field="totalElements"
            page-index-key="page"
            page-size-key="pageSize"
            method="get"
            @selection-change="handleSelectionChange">
          <template slot="button">
            <el-button size="mini" @click="openCommentDialog()">添加评论</el-button>
            <el-button type="danger" size="mini" v-if="selectedIdList.length>0 "
                       @click="batchDelete()">批量删除
            </el-button>
            <el-button type="primary" size="mini" v-if="selectedIdList.length>0 "
                       @click="batchPublish()">批量发布
            </el-button>
            <el-button type="primary" size="mini" v-if="selectedIdList.length>0 "
                       @click="batchUnPublish()">批量取消发布
            </el-button>
            <el-button type="primary" size="mini" v-if="selectedIdList.length>0 "
                       @click="setStar=true">批量评分
            </el-button>
          </template>
          <template slot-scope="scope" slot="star">
            <el-rate disabled v-model="scope.row.star"></el-rate>
          </template>
          <template slot-scope="scope" slot="reviewsOperations">
            <el-button plain size="mini" type="primary" @click="openEditDialog(scope.row)">修改</el-button>
            <el-button plain size="mini" type="primary" v-if="scope.row.status===1"
                       @click="unPublishReviews(scope.row.id)">隐藏
            </el-button>
            <el-button plain size="mini" type="primary" v-if="scope.row.status===0" @click="publishReviews(scope.row.id)">
              发布
            </el-button>
            <el-button plain size="mini" type="danger" @click="deleteReviews(scope.row.id)">删除</el-button>
          </template>
        </table-pagination>

      </div>
    </el-card>

    <el-dialog title="批量评分" :visible.sync="setStar" width="30%" center>
      <div class="domain-text">请对选中的评论设置评分</div>
      <div class="radio-text">
        <el-rate v-model="star"
                 :colors="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                 :allow-half="false"
                 show-score
                 text-color="rgb(244, 90, 25)"
                 score-template="{value}"
                 style="height: 40px;margin-top: 10px"
                 class="rate-d"
        >

        </el-rate>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="setStar = false">取 消</el-button>
      <el-button type="primary" @click="batchStar()">确 定</el-button>
    </span>
    </el-dialog>
    <el-dialog title="评论" :visible.sync="commentDialogVisible" width="1000px" center>
      <el-form ref="commentForm" :model="reviews" label-width="100px" label-position="top" style="text-align: left; max-height: 700px; overflow-y: scroll;">
        <template v-for="(item, index) in reviews.comment">
          <div :key="index" class="reviewsList_item">
            <h5>{{ index + 1 }} <i style="margin-left: 12px;font-size: 16px;color: #333" class="el-icon-delete"
                                   @click="handleRemoveLevel(index)" v-if="reviews.comment.length > 1"></i></h5>
            <div class="marketing-row-conditions">
              <el-row>
                <el-col :span="8">
                  <el-form-item class="item" :prop="'comment.' + index + '.star'" label="评论分数"
                                :rules="[{required: true, message: '内容不能为空', trigger: 'blur'}]">
                    <el-rate v-model="item.star"
                             :colors="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                             :allow-half="false"
                             show-score
                             text-color="rgb(244, 90, 25)"
                             score-template="{value}"
                             class="rate-d"
                    >
                    </el-rate>
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="commentDialogVisible">
                  <el-form-item label="评论日期" class="item" :prop="'comment.' + index + '.commentTime'"
                                :rules="[{required: true, message: '请选择日期', trigger: 'blur'}]">
                    <el-date-picker
                        v-model="item.commentTime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetime"
                        placeholder="选择日期时间"
                        style="width:260px"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="评论人" class="item" :prop="'comment.' + index + '.memberName'"
                                :rules="[{required: true, message: '内容不能为空', trigger: 'blur'}]">
                    <el-input v-model="item.memberName" placeholder="请输入评论人" style="width:260px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="18">
                  <el-form-item label="评论内容" class="item" :prop="'comment.' + index + '.content'"
                                :rules="[{required: true, message: '内容不能为空', trigger: 'blur'}]">
                    <el-input
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 6}"
                        placeholder="请输入内容"
                        v-model="item.content"
                        style="width:670px"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="评论图片" class="item">
                <upload-file accept="image/jpeg,image/jpg,image/png"
                             ref="uploadAdd"
                             :multiple="true"
                             :limit="5"
                             :fileType="['png', 'jpg', 'jpeg']"
                             :isShowTip="true"
                             :lazy="true"
                             :size="120"
                             :responseFn="handleResponse"
                             :action="uploadPath"
                             title="图片"
                             v-model="item.images"
                >
                </upload-file>
                <p>最多上传五张评论图片</p>
              </el-form-item>
              <div class="btn_line">
                <el-button @click="handleAddComment">添加评论</el-button>
              </div>
            </div>
          </div>
        </template>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="commentDialogVisible = false">取 消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSaveComment('commentForm')">确 定</el-button>
    </span>
    </el-dialog>

    <el-dialog title="编辑评论" :visible.sync="updateCommentDialogVisible" width="1000px" center>
      <el-form ref="updateCommentForm" :model="updateReviews" label-width="100px" label-position="top">
        <div class="marketing-row-conditions">
          <el-row>
            <el-col :span="8">
              <el-form-item class="item" prop="star" label="评论分数"
                            :rules="[{required: true, message: '内容不能为空', trigger: 'blur'}]">
                <el-rate v-model="updateReviews.star"
                         :colors="['rgb(244, 90, 25)', 'rgb(244, 90, 25)', 'rgb(244, 90, 25)']"
                         :allow-half="false"
                         show-score
                         text-color="rgb(244, 90, 25)"
                         score-template="{value}"
                         class="rate-d"
                >
                </el-rate>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="评论日期" class="item" prop="commentTime"
                            :rules="[{required: true, message: '请选择日期', trigger: 'blur'}]">
                <el-date-picker
                    v-model="updateReviews.commentTime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    placeholder="选择日期时间"
                    style="width:260px"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="评论人" class="item" prop="memberName"
                            :rules="[{required: true, message: '内容不能为空', trigger: 'blur'}]">
                <el-input v-model="updateReviews.memberName" placeholder="请输入评论人" style="width:260px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="评论内容" class="item" prop="content"
                            :rules="[{required: true, message: '内容不能为空', trigger: 'blur'}]">
                <el-input
                    type="textarea"
                    :autosize="{ minRows: 4, maxRows: 6}"
                    placeholder="请输入内容"
                    v-model="updateReviews.content"
                    style="width:670px"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="评论图片" class="item">
            <upload-file accept="image/jpeg,image/jpg,image/png"
                         ref="uploadEdit"
                         :multiple="true"
                         :limit="5"
                         :fileType="['png', 'jpg', 'jpeg']"
                         :isShowTip="true"
                         :lazy="true"
                         :size="120"
                         :responseFn="handleResponse"
                         :action="uploadPath"
                         title="图片"
                         v-model="updateReviews.images"
            >
            </upload-file>
            <p>最多上传五张评论图片</p>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="updateCommentDialogVisible = false">取 消</el-button>
      <el-button type="primary" :loading="submitLoading"
                 @click="handleUpdateComment('updateCommentForm')">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import TablePagination from '_c/Tables/table-pagination';
import uploadFile from '_c/Upload/uploadFile';
import {
    getSpuReviewsPage,
    getSpuReviewsDetail,
    deleteReviews,
    publishReviews,
    unPublishReviews, starReviews, addSpuReviews, updateSpuReviews
} from '@/api/reviews';
import {mapGetters} from 'vuex';
import {utcFormat} from '@/utils/filters';

export default {
    name: 'reviews-detail',
    components: {TablePagination, uploadFile},
    data () {
        return {
            spuId: this.$route.params.id,
            commentDialogVisible: false,
            updateCommentDialogVisible: false,
            setStar: false,
            submitLoading: false,
            star: 5,
            spuInfo: {},
            updateReviews: {
                id: '',
                content: '',
                commentTime: '',
                images: '',
                star: '',
                memberName: ''
            },
            reviews: {
                comment: [
                    {
                        siteId: '',
                        spuId: '',
                        content: '',
                        commentTime: '',
                        images: [],
                        star: 5,
                        memberName: '',
                        status: ''
                    }
                ]
            },
            fixOption: {fixedHeader: true, bottomOffset: 80},
            columns: [
                {label: '', type: 'selection'},
                {
                    label: '评论人',
                    prop: 'memberName'
                },
                {
                    label: '评论星级',
                    prop: 'star',
                    slotName: 'star'
                },
                {
                    label: '评论内容',
                    prop: 'content',
                    showOverflowTooltip: true
                },
                {
                    label: '评论状态',
                    prop: 'status',
                    render: row => {
                        let status = row.status;
                        if (status === 1) {
                            return '已发布';
                        } else {
                            return '未发布';
                        }
                    }

                },
                {
                    label: '评论时间',
                    prop: 'commentTime',
                    render: row => {
                        return utcFormat(row.commentTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                    },
                    width: '180px'
                },
                {label: '操作', slotName: 'reviewsOperations', width: 250}
            ],
            tableData: [],
            selectedList: [],
            selectedIdList: [],
            pageParams: {
                page: 1,
                pageSize: 20,
                status: '',
                stars: [],
                content: ''
            },
            formOptions: {
                showResetBtn: true,
                showSearchBtn: true,
                inline: false,
                labelWidth: 120,
                submitBtnText: '查询',
                size: 'small',
                resetBtnCallback: () => {
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                },
                forms: [
                    {prop: 'content', label: '内容', placeholder: '评论内容'},
                    {
                        prop: 'stars',
                        label: '评分',
                        itemType: 'select',
                        placeholder: '请选择评分',
                        multiple: true,
                        options: [
                            // {value: '', label: '全部评分'},
                            {value: 1, label: '1星'},
                            {value: 2, label: '2星'},
                            {value: 3, label: '3星'},
                            {value: 4, label: '4星'},
                            {value: 5, label: '5星'}
                        ]
                    },
                    {
                        prop: 'status',
                        label: '发布状态：',
                        itemType: 'select',
                        placeholder: '请选择发布状态',
                        options: [
                            {label: '全部', value: ''},
                            {label: '已发布', value: 1},
                            {label: '未发布', value: 0}
                        ]
                    }
                ]
            }
        };
    },
    computed: {
        ...mapGetters(['timeZone']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        uploadPath () {
            return process.env.VUE_APP_BASE_API + '/upload-file?siteId=' + this.siteId;
        }
    },
    mounted () {
        this.getSpuInfo();
    },
    methods: {
        handleResponse (response, file, fileList) {
            return response;
        },
        openCommentDialog () {
            this.reviews.comment = [];
            this.commentDialogVisible = true;
            this.handleAddComment();
        },
        handleAddComment () {
            this.reviews.comment.push({
                siteId: this.siteId,
                spuId: this.spuId,
                status: 1,
                content: '',
                commentTime: '',
                images: '',
                star: 5,
                memberName: ''
            });
        },
        openEditDialog (updateReviews) {
            this.updateReviews = {
                id: '',
                content: '',
                commentTime: '',
                images: [],
                star: '',
                memberName: ''
            };
            this.updateCommentDialogVisible = true;
            this.updateReviews = Object.assign(this.updateReviews, {
                id: updateReviews.id,
                star: updateReviews.star,
                commentTime: utcFormat(updateReviews.commentTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone),
                memberName: updateReviews.memberName,
                content: updateReviews.content
            });
            if (updateReviews.images) {
                this.updateReviews.images = updateReviews.images.split(',');
            }
        },
        getSpuInfo () {
            getSpuReviewsDetail(this.siteId, this.spuId).then((res) => {
                this.spuInfo = res.data;
            });
        },
        batchDelete () {
            this.$confirm('确认删除这些评论?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteReviews({siteId: this.siteId, ids: this.selectedIdList.join(',')}).then(res => {
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                    this.getSpuInfo();
                });
            });
        },
        batchPublish () {
            this.$confirm('确认发布这些评论?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                publishReviews({siteId: this.siteId, ids: this.selectedIdList.join(',')}).then(res => {
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                    this.getSpuInfo();
                });
            });
        },
        batchUnPublish () {
            this.$confirm('确认取消发布这些评论?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                unPublishReviews({siteId: this.siteId, ids: this.selectedIdList.join(',')}).then(res => {
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                    this.getSpuInfo();
                });
            });
        },
        batchStar () {
            starReviews({siteId: this.siteId, star: this.star, ids: this.selectedIdList.join(',')}).then(res => {
                this.setStar = false;
                this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                this.getSpuInfo();
            });
        },
        unPublishReviews (id) {
            unPublishReviews({siteId: this.siteId, ids: id}).then(res => {
                this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                this.getSpuInfo();
            });
        },
        publishReviews (id) {
            publishReviews({siteId: this.siteId, ids: id}).then(res => {
                this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                this.getSpuInfo();
            });
        },
        deleteReviews (id) {
            deleteReviews({siteId: this.siteId, ids: id}).then(res => {
                this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                this.getSpuInfo();
            });
        },
        getData (params) {
            return new Promise((resolve, reject) => {
                this.pageParams.pageSize = params.pageSize;
                let parameters = {
                    siteId: this.siteId,
                    spuId: this.spuId,
                    stars: params.stars && params.stars.join(',')
                };
                getSpuReviewsPage({...params, ...parameters}).then((res) => {
                    let records = res.records;
                    if (records == null || records.length === 0) {
                        resolve(res);
                        return false;
                    }
                    res.records = records;
                    this.tableData = records;
                    resolve(res);
                });
            });
        },
        handleSaveComment (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.submitLoading = true;
                    this.reviews.comment.forEach(comment => {
                        comment.commentTime = new Date(comment.commentTime + ' UTC' + this.timeZone).getTime() + '';
                        if (comment.images) {
                            comment.images = comment.images.join(',');
                        }
                    });
                    addSpuReviews(this.reviews.comment).then(res => {
                        if (res.code === '200') {
                            this.submitLoading = false;
                            this.$message.success('保存成功');
                            this.commentDialogVisible = false;
                            this.$refs[name].resetFields();
                            this.$refs.uploadAdd[0].clear();
                            this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                            this.getSpuInfo();
                        }
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        handleUpdateComment (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.submitLoading = true;
                    this.updateReviews.commentTime = new Date(this.updateReviews.commentTime + ' UTC' + this.timeZone).getTime() + '';
                    if (this.updateReviews.images) {
                        this.updateReviews.images = this.updateReviews.images.join(',');
                    }
                    updateSpuReviews(this.updateReviews).then(res => {
                        if (res.code === '200') {
                            this.submitLoading = false;
                            this.$message.success('保存成功');
                            this.updateCommentDialogVisible = false;
                            this.$refs[name].resetFields();
                            this.$refs.uploadEdit.clear();
                            this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                            this.getSpuInfo();
                        }
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        handleSelectionChange (records) {
            if (records && records.length > 0) {
                let tempIdList = [];
                records.forEach(item => {
                    tempIdList.push(item.id);
                });
                this.selectedIdList = tempIdList;
                this.selectedList = records;
            } else {
                this.selectedIdList = [];
                this.selectedList = [];
            }
        },
        handleRemoveLevel (index) {
            this.reviews.comment.splice(index, 1);
        }
    }
};
</script>

<style scoped lang="scss">
.oct-container__data_inner {
  display: flex;
  padding: 20px 40px;
  color: #212121;
  font-size: 14px;

  .info {
    width: 383px;
    margin-right: 80px;
    color: #212121;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .header {
      margin: 0;
      max-width: 383px;
      color: #212121;
      font-size: 14px;
      font-weight: 400;
    }

    .two_line_text_truncate {
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      word-break: break-all;
    }

    .stars {
      margin: 15px 0;
    }

    .footer {
      .item:first-child {
        margin-right: 20px;
      }
    }
  }

  .grade {
    .row {
      width: 270px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .progress {
        width: 110px;
      }
    }
  }
}
.btn_line{
  width: 100%;
  height: 60px;
  background-color: white;
  position: absolute;
  bottom: 70px;
  left: 0px;
  padding-left: 40px;
  display: flex;
  align-items: center;
  box-shadow: inset 0 2px 2px 0px #e6e9f0;
  z-index: 100;
}
.reviewsList_item{
  border-bottom: 1px solid #d8deec;
}
</style>

<style lang="scss">
.rate-d .el-rate__icon{
  font-size: 32px;
}
</style>
